﻿using System;
using Hammock;
using RedBit.UserVoice.Model;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Linq;
using RedBit.UserVoice.OAuth;
using Hammock.Web;

namespace RedBit.UserVoice.Services
{
    public class UVCommentService : BaseUVApi
    {
        #region Get Comments for Suggestion
        public static void GetCommentsForSuggestion(string forumId, int suggestionId, Action<UVResponse<ICollection<UVComment>>> handler)
        {
            GetCommentsForSuggestion(forumId, suggestionId, 1, handler);
        }

        public static void GetCommentsForSuggestion(string forumId, int suggestionId, int page, Action<UVResponse<ICollection<UVComment>>> handler)
        {
            var client = new RestClient
            {
                Authority = string.Format(UserVoiceConstants.URL_TEMPLATE, UserVoiceAPI.AppName),
            };

            var request = new RestRequest
            {
                Path = string.Format( UserVoiceConstants.GET_COMMENTS_SUFFIX, forumId, suggestionId)
            };

            request.AddParameter("client", UserVoiceAPI.Key);
            request.AddParameter("page", page.ToString());

            client.BeginRequest(request, HandleGetCommentsResponse, handler);
        }

        private static void HandleGetCommentsResponse(RestRequest rq, RestResponse rs, object token)
        {
            var response = JObject.Parse(rs.Content);
            var jsonObjects = response["comments"] as JArray;

            var error = ParseError(response);
            var comments =
                from obj in jsonObjects
                select new UVComment
                {
                    Id = obj["id"].Value<int>(),
                    Text = obj["text"].Value<string>(),
                    CreatedAt = obj["created_at"].Value<DateTime>(),
                    User = new OAuthUser()
                    {
                        //TODO: Parse the rest of the object.
                        Id = obj["creator"]["id"].Value<string>(),
                        AvatarUrl = obj["creator"]["avatar_url"].Value<string>(),
                        Name = obj["creator"]["name"].Value<string>(),
                    }
                };

            var handler = token as Action<UVResponse<ICollection<UVComment>>>;

            handler(new UVResponse<ICollection<UVComment>> { Model = comments.ToList(), Error = error });
        }
        #endregion  Get Comments for Suggestion

        #region Comment On Suggestion
        public static void CommentOnSuggestion(string forumId, string suggestionId, UVComment comment, Action<UVResponse<UVComment>> responseHandler)
        {
            //// Create Credentials
            var credentials = BuildCredentials();

            credentials.Token = UserVoiceAPI.AccessToken.Key;
            credentials.TokenSecret = UserVoiceAPI.AccessToken.Secret;


            var client = new RestClient
            {
                Authority = string.Format(UserVoiceConstants.URL_TEMPLATE, UserVoiceAPI.AppName),
                Credentials = credentials,
                Method = WebMethod.Post
            };

            var request = new RestRequest
            {
                Path = string.Format(UserVoiceConstants.COMMENT_ON_SUGGESTION_SUFFIX, forumId, suggestionId),
            };

            request.AddParameter("comment%5Btext%5D", comment.Text);

            client.BeginRequest(request, HandleCommentOnSuggestion, responseHandler);
        }


        private static void HandleCommentOnSuggestion(RestRequest rq, RestResponse rs, object token)
        {
            //TODO: Handle Errors
            var handler = token as Action<UVResponse<UVComment>>;
            var response = JObject.Parse(rs.Content);

            var obj = response["comment"];

            var error = ParseError(response);
            var comment = new UVComment()
            {
                Id = obj["id"].Value<int>(),
                Text = obj["text"].Value<string>(),
                CreatedAt = obj["created_at"].Value<DateTime>(),
                User = new OAuthUser()
                {
                    //TODO: Parse the rest of the object.
                    Id = obj["creator"]["id"].Value<string>(),
                    AvatarUrl = obj["creator"]["avatar_url"].Value<string>(),
                    Name = obj["creator"]["name"].Value<string>(),
                }
            };

            handler(new UVResponse<UVComment> { Model = comment, Error = error });
        }
        #endregion Comment On Suggestion

    }
}
